package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 接收售货机状态消息，验证售货机是否故障，创建维修工单
 */
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VmsStatusTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //1. json转成对象
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        //2.过滤出false(损坏)的状态码
        //获取售货机上报的信息
        List<StatusInfo> statusInfo = vmStatusContract.getStatusInfo();
        //过滤出所有false（损坏）的信息，排除true(正常)的信息
        List<StatusInfo> collect = statusInfo.stream()
                //each.isStatus()：因为each中boolean类型是基本数据类型，所以生成会用is开头
                //                  如果使用包装类型（Boolean）就会生成get开头的
                .filter(each -> !each.isStatus())
                .collect(Collectors.toList());

        //查询当前售货机的信息（主要是要当前售货机的所属区域）
        VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
        //查询分数最少的维修工单的员工
        Integer userId = taskService.getLeastUser(vmInfo.getRegionId(), false);
        //开始生成维修工单
        if (!CollectionUtils.isEmpty(collect)) {
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(VMSystem.AUTO_CREATE_TYPE);
            taskViewModel.setInnerCode(vmStatusContract.getInnerCode());
            taskViewModel.setUserId(userId);
            taskViewModel.setAssignorId(VMSystem.SYSTEM_AUTO_CREATE);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
            taskViewModel.setDesc(jsonMsg);
            taskService.createTask(taskViewModel);
        }
    }
}
